// Package version 定义一个统一的版本号格式
package version

import (
	"encoding/json"
	"fmt"
	"runtime"

	"github.com/gosuri/uitable"
)

var (
	// 语义版本号
	GitVersion = "v0.0.0-master+$Format:%h$"
	// 编译时间（ISO8601格式），通过$(date -u +'%Y-%m-%dT%H:%M:%SZ')输出
	BuildDate = "1970-01-01T00:00:00Z"
	// git提交sha1, 通过$(git rev-parse HEAD)输出
	GitCommit = "$Format:%H$"
	// GitTreeState state of git tree, either "clean" or "dirty".
	GitTreeState = ""
)

// Version 版本结构体
type Version struct {
	GitVersion   string `json:"gitVersion"`
	GitCommit    string `json:"gitCommit"`
	GitTreeState string `json:"gitTreeState"`
	BuildDate    string `json:"buildDate"`
	GoVersion    string `json:"goVersion"`
	Compiler     string `json:"compiler"`
	Platform     string `json:"platform"`
}

// String 返回可读的版本信息
func (v Version) String() string {
	if s, err := v.Text(); err == nil {
		return string(s)
	}

	return v.GitVersion
}

// ToJSON 将版本信息转换为JSON格式
func (v Version) ToJSON() string {
	s, _ := json.Marshal(v)

	return string(s)
}

// Text 将版本信息编码
func (v Version) Text() ([]byte, error) {
	table := uitable.New()
	table.RightAlign(0)
	table.MaxColWidth = 80
	table.Separator = " "
	table.AddRow("gitVersion:", v.GitVersion)
	table.AddRow("gitCommit:", v.GitCommit)
	table.AddRow("gitTreeState:", v.GitTreeState)
	table.AddRow("buildDate:", v.BuildDate)
	table.AddRow("goVersion:", v.GoVersion)
	table.AddRow("compiler:", v.Compiler)
	table.AddRow("platform:", v.Platform)

	return table.Bytes(), nil
}

// Get 返回版本信息
func Get() Version {
	return Version{
		GitVersion:   GitVersion,
		GitCommit:    GitCommit,
		GitTreeState: GitTreeState,
		BuildDate:    BuildDate,
		GoVersion:    runtime.Version(),
		Compiler:     runtime.Compiler,
		Platform:     fmt.Sprintf("%s/%s", runtime.GOOS, runtime.GOARCH),
	}
}
